import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  // 后端配置 - 可以通过环境变量覆盖
  const BACKEND_TYPE = env.VITE_BACKEND_TYPE || 'go'
  const BACKEND_PORT = env.VITE_BACKEND_PORT || ''

  // 根据后端类型确定默认端口（如果没有指定 BACKEND_PORT）
  const getDefaultPort = (type: string) => {
    switch (type) {
      case 'nodejs':
        return '3000'
      case 'go':
      default:
        return '3001'
    }
  }

  // 最终使用的端口
  const backendPort = BACKEND_PORT || getDefaultPort(BACKEND_TYPE)

  console.log(`🔗 前端代理配置: ${BACKEND_TYPE} 后端 -> http://127.0.0.1:${backendPort}`)

  return {
    plugins: [vue()],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      host: '0.0.0.0',
      port: 5173,
      proxy: {
        '/api': {
          target: `http://127.0.0.1:${backendPort}`,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '/api')
        }
      }
    },
    optimizeDeps: {
      exclude: ['lockdown-install.js']  // 排除 lockdown-install.js
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['vue', 'vue-router', 'axios']
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true
        }
      }
    }
  }
}) 